<template>
  <div>
    <el-form class="query-form" @submit.native.prevent :inline="true">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          auto-top
          placeholder="所属地"
          @change="getData"
        ></select-address>
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="params.customer_name"
          style="width: 10rem"
          :clearable="true"
          placeholder="主体名称查询"
          @change="getData"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="params.lender_idcard"
          :clearable="true"
          placeholder="身份证号码"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="params.public_status"
          style="width: 8rem"
          @change="getData"
          clearable
          placeholder="公示状态"
        >
          <el-option
            v-for="(key, value) of enumPublicStatus"
            :key="value"
            :value="value"
            :label="key"
          ></el-option>
        </el-select>
      </el-form-item>

      <!--<el-form-item>-->
      <!--<el-button @click="getData()">查询</el-button>-->
      <!--</el-form-item>-->

      <el-form-item class="float-right">
        <el-button type="primary" icon="el-icon-printer" @click="handlePrint()">打印</el-button>
        <el-button
          type="primary"
          icon="el-icon-document"
          :loading="exportLoading"
          @click="publicVisible = true"
        >
          我的公示
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="handleDownload()"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>
    <my-publicity :visible.sync="publicVisible" :refle="true"></my-publicity>

    <c-table
      border
      ref="multipleTable"
      name="table"
      class="table-sm"
      v-loading="loading"
      :stripe="false"
      :columns="tableColumns"
      :data="tableData"
      @select="handleSelectChange"
      @select-all="handleSelectChange"
    >
      <template v-slot:operations="scope">
        <el-tooltip
          effect="light"
          placement="bottom"
          content="公示反馈"
          v-if="scope.row.publicStatus === 1"
        >
          <el-button type="text" class="py-0 px-2" @click="handleEdit(scope.row)">
            <i class="fa fa-edit"></i>
          </el-button>
        </el-tooltip>
      </template>
      <template v-slot:status="scope">
        <div class="badge" :title="scope.row.public_des || ''">
          {{ enumPublicStatus[scope.row.public_status] || '-' }}
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div class="d-flex">
        <!--<el-checkbox v-model="isSelectAll"-->
        <!--:label="isSelectAll?'反选':'全选'"-->
        <!--border-->
        <!--@change="handleSelectAllChange"></el-checkbox>-->
        <!--<el-button @click="handleClearAll"-->
        <!--v-if="tablePages>1">清空选择</el-button>-->
      </div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <publicity-print
      :visible.sync="detailVisible"
      :data-list="selects"
      @success="handlePublicSuccess"
    ></publicity-print>

    <el-dialog
      top="30px"
      width="600px"
      title="公示反馈"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="feedbackVisible"
    >
      <p class="text-center">请填写公示未通过说明：</p>

      <el-input
        type="textarea"
        class="mb-3"
        rows="5"
        placeholder="请填写公示未通过说明"
        v-model="feedback"
      ></el-input>

      <div class="text-center">
        <el-button class="btn-long" :loading="feedbackLoading" @click="handleFeedbackSubmit">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import SelectAddress from '@/components/select/SelectAddress'
import PublicityPrint from '@/gov/views/business/PublicityPrint'
import { enumPublicStatus } from '@/gov/plugins/enum'
import MyPublicity from './MyPublicity'

const PUBLIC_STATUS_UNDO = 0
const PUBLIC_STATUS_DOING = 1
const PUBLIC_STATUS_FINISH = 2
const publicStatus = {
  0: PUBLIC_STATUS_UNDO,
  1: PUBLIC_STATUS_DOING,
  2: PUBLIC_STATUS_FINISH,
  3: PUBLIC_STATUS_FINISH,
}

export default {
  components: {
    SelectAddress,
    PublicityPrint,
    MyPublicity,
  },
  props: {},
  data() {
    return {
      tableName: 'customer_related',
      tableId: '',
      enumPublicStatus,
      publicVisible: false,
      params: {
        index: 1,
        size: 15,
        customer_name: '',
        lender_idcard: '',
        address_code: '',
        public_status: '',
        'submit_type.eq': '',
        'res_status.eq': 1,
      },
      loading: false,

      tableData: [],
      tableCount: 0,
      tablePages: 0,
      tableColumns: [
        { attrs: { type: 'selection', align: 'center', width: '55', selectable: this.onSelect } },
        { attrs: { label: '所属地区', prop: 'address' } },
        { attrs: { label: '借款主体', prop: 'customer_name' } },
        { attrs: { label: '借款人', prop: 'corp_name' } },
        { attrs: { label: '身份证号码', prop: 'lender_idcard' } },
        { attrs: { label: '拟贷款银行', prop: 'bank_name' } },
        { attrs: { label: '拟发放贷款金额（万元）', prop: 'approved_funds', align: 'center' } },
        {
          attrs: { label: '公示剩余时间', prop: 'publicStatusLabel', align: 'center' },
          process: v => v || '-',
        },
        { attrs: { label: '公示状态', prop: 'public_status', align: 'center' }, slot: 'status' },
        // process: v => enumPublicStatus[v] || '-'
        {
          attrs: { label: '操作', align: 'center' },
          slot: 'operations',
        },
      ],
      // 多选，打印
      pageSelect: {},
      isSelectAll: false,
      selects: [],

      detailVisible: false,

      //
      exportLoading: false,

      feedbackVisible: false,
      feedbackRow: {},
      feedback: '',
      feedbackLoading: false,
    }
  },
  computed: {
    ...mapGetters(['org']),
  },
  watch: {},
  created() {
    this.params.address_code = this.$utils.getAddressCode()
    let orgClass = this.org.orgClass
    this.params['submit_type.eq'] = orgClass === 'org_gov_ny' ? '1' : '4'
    this.getData()
  },
  mounted() {},
  methods: {
    onSelect(row) {
      return +row.public_status === 0
    },
    async getData() {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, this.params, {
          N1public_status: 'asc',
          N2create_time: 'desc',
          N3public_date: 'desc',
        })
      )
      this.loading = false

      const data = (res && res.data) || {}
      this.tableData = (data.data || []).map(item => {
        item.publicStatus = publicStatus[item.public_status] || PUBLIC_STATUS_UNDO

        const leftDays = +item.left_days || 0
        if (item.publicStatus === PUBLIC_STATUS_UNDO) {
          item.publicStatusLabel = '待打印公示'
        } else {
          item.publicStatusLabel = leftDays > 0 ? `${leftDays}天` : '已到期'
        }

        return item
      })
      this.tableCount = data.totalCount || 0
      this.tablePages = data.totalPages || 0

      this.$nextTick(() => {
        this.toggleSelection(this.pageSelect[this.params.index])
      })
    },

    // 分页及选择逻辑
    handleSelectChange(selection) {
      this.pageSelect[this.params.index] = selection.map(row => {
        return { ...row }
      })
      const len = this.pageSelect[this.params.index].length
      this.isSelectAll = len && len === this.tableData.length
    },
    handleSelectAllChange() {
      const $tableRef = this.$refs.multipleTable.$refs.table
      if ($tableRef) {
        $tableRef.toggleAllSelection(this.isSelectAll)
      }
    },
    handleClearAll() {
      this.pageSelect = {}
      this.isSelectAll = false
      this.toggleSelection()
    },
    toggleSelection(rows) {
      const $tableRef = this.$refs.multipleTable.$refs.table
      if (!$tableRef) {
        return
      }
      if (!rows) {
        this.isSelectAll = false
        return $tableRef.clearSelection()
      }

      // rows是缓存的数据，需要转化为当前tableData各项的引用
      const indexArr = rows.map(row => {
        return this.tableData.findIndex(it => it.customer_related_id === row.customer_related_id)
      })

      indexArr.forEach(index => {
        if (index > -1) {
          $tableRef.toggleRowSelection(this.tableData[index])
        }
      })
    },

    handlePublicSuccess() {
      this.handleClearAll()
      this.params.index = 1
      this.getData()
    },
    handleEdit(row) {
      this.feedbackRow = { ...row }
      this.feedback = ''
      this.feedbackVisible = true
    },
    handleFeedbackBeforeClose() {
      this.feedback = ''
      this.feedbackVisible = false
    },
    async handleFeedbackSubmit() {
      if (!this.feedback) {
        return this.$message.error('请填写公示未通过说明')
      }

      this.feedbackLoading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData(
          this.$serviceName,
          'customer_related',
          this.feedbackRow.customer_related_id,
          {
            public_status: 3,
            public_des: this.feedback,
          }
        )
      )
      this.feedbackLoading = false
      if (res) {
        this.getData()
        this.handleFeedbackBeforeClose()
        return this.$message.success('操作成功')
      }
      this.$message.error('操作失败，请重试！')
    },
    handlePrint() {
      this.selects = Object.freeze(
        Object.keys(this.pageSelect)
          .map(key => {
            return this.pageSelect[key] || []
          })
          .reduce((prev, cur) => {
            prev.push.apply(prev, cur)
            return prev
          }, [])
      )

      if (!this.selects.length) {
        return this.$message.error('请先选择主体')
      }

      this.detailVisible = true
    },
    async handleDownload() {
      const { index, size, ...params } = this.params // eslint-disable-line
      const exportParams = {
        service: this.$serviceName,
        table: this.tableName,
        params: params,
        filename: '公示发布.xlsx',
      }

      this.exportLoading = true
      await this.$utils.promise(this.$api.exportData(exportParams))
      this.exportLoading = false
    },
  },
}
</script>

<style lang="scss" scoped></style>
